<?php
/**
 * @Author: king
 * @Last Modified by:   king
 * Date: 2018/10/31
 * Time: 14:38
 */

namespace App\Models\Api;
use App\Exceptions\ApiException;
use App\Models\Api\Base;
use App\Tools\Astrolog\Acg;
use Cache;

class FateCity extends Base
{
    protected $table = 'wechat.app_fate_city_user';

    /**
     * @param $map
     * @return array|bool|mixed
     * @throws ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUserFateCitys($map)
    {
        $result = false;
        if (intval($this->cache_on) >= 1) $result = Cache::get('fate_city_' . $map['rid']);


        if ($result === false || empty($result)) {
            $fate_city = config('map.fate_city');
            $fate_city_name = config('map.fate_city_name');
            $fate_city_loc = config('map.fate_city_loc');
            $fate_city_des = config('map.fate_city_title');// 命运之城提示窗信息

            // 当前无缓存，先查库（是否计算过）
            try {
                $data = $this->table('wechat.app_fate_city_user')
                    ->alias('fcu')
                    ->join('wechat.app_map m', 'fcu.mid=m.id', 'LEFT')
                    ->field('fcu.fcid,m.id,m.longitude,m.latitude')
                    ->where(['uid' => $map['uid'], 'rid' => $map['rid']])
                    ->selectOrFail();
                $result = [];
                foreach ($data as $d) {
                    // key 为经纬度id 即城市id
                    if (isset($result[$d['id']]['name'])) {
                        $result[$d['id']]['name'] .= '、' . $fate_city_name[$d['fcid']];
                        $strlen = mb_strlen($result[$d['id']]['name']);
                        if ($strlen == 9) {
                            $result[$d['id']]['icon'] = $fate_city[10];
                            $result[$d['id']]['loc_icon'] = $fate_city_loc[10];
                            $result[$d['id']]['description'] = $fate_city_des[10];
                        }
                    } else {
                        $result[$d['id']]['name'] = $fate_city_name[$d['fcid']];
                        $result[$d['id']]['icon'] = $fate_city[$d['fcid']];
                        $result[$d['id']]['loc_icon'] = $fate_city_loc[$d['fcid']];
                        $result[$d['id']]['description'] = $fate_city_des[$d['fcid']];
                        $result[$d['id']]['longitude'] = $d['longitude'];
                        $result[$d['id']]['latitude'] = $d['latitude'];
                    }
                }

                // 首次运算命运之城数据，计算后入库
            } catch (\Exception $e) {

                $citys = config('city.lon_lat');// 经纬度
                $map['fate'] = true;
                $score = [];
                if (!empty($citys)) {
                    foreach ($citys as $k => $city) {
                        $map['point_longitude'] = $city[0];
                        $map['point_latitude'] = $city[1];
                        $score[$k] = (new Acg())->getRecommendedInfo($map);
                    }
                }

                $list = $result = $fates = [];
                foreach ($score as $i => $c) foreach ($c as $j => $s) $list[$j][$i] = $s;

                foreach ($list as $fate => $l) {
                    $max = max($l);

                    if ($max <= 0) continue;

                    $fate_name = $fate_city_name[$fate];
                    foreach ($l as $key => $m) {
                        // 获取最大值城市 key
                        if ($m == $max) {
                            $lon_lat = $citys[$key];// 命运之城城市经纬度
                            if (isset($result[$key]['name'])) {
                                // 当前城市属于多个命运之城
                                $result[$key]['name'] .= '、' . $fate_name;
                                $result[$key]['icon'] = $fate_city[10];
                                $result[$key]['loc_icon'] = $fate_city_loc[10];
                                $result[$key]['description'] = $fate_city_des[10];
                            } else {
                                // 第一条
                                $result[$key] = [
                                    'icon' => $fate_city[$fate],
                                    'loc_icon' => $fate_city_loc[$fate],
                                    'name' => $fate_name,
                                    'description' => $fate_city_des[$fate],
                                    'longitude' => $lon_lat[0],
                                    'latitude' => $lon_lat[1]
                                ];
                            }
                            $fates[] = [
                                'id' => $fate,
                                'uid' => $map['uid'],
                                'rid' => $map['rid'],
                                'longitude' => $lon_lat[0],
                                'latitude' => $lon_lat[1]
                            ];
                        }
                    }
                }

                $this->saveFateCity($fates);// 保存命运之城入库
            }

            foreach ($result as $k => $r) {
                $fate_citys = array_filter(explode('、', $r['name']));

                $fate_city_count = count($fate_citys);

                if ($fate_city_count > 1) {


                    if ($fate_city_count == 2) {
                        $replace_str = '既是你的' . $fate_citys[0] . '，又是你的' . $fate_citys[1];

                        // 这座城市对你来说可谓祥云笼罩，大吉大利，既是你的XX之城，又是你的XX之城。想知道它会给你带来哪些具体好处，可点击进入城市详情页面查看。
                        $result[$k]['description'] = str_replace('[city]', $replace_str, $r['description']);
                    } else {
                        $replace_str = '分别是你的';

                        for ($i = 0; $i < $fate_city_count - 1; $i++) $replace_str .= $fate_citys[$i] . '、';

                        $replace_str = mb_substr($replace_str, 0, -1);

                        $replace_str .= '和' . $fate_citys[$fate_city_count - 1];

                        // 这座城市对你来说可谓祥云笼罩，大吉大利，分别是你的XX之城、XX之城、XX之城和XX之城。想知道它会给你带来哪些具体好处，可点击进入城市详情页面查看。
                        $result[$k]['description'] = str_replace('[city]', $replace_str, $r['description']);
                    }
                }
            }
            $result = array_values($result);

            Cache::set('fate_city_' . $map['rid'], $result, 86400 * 3);
        }
        return $result;
    }

    /**
     * @param array $data
     */
    protected function saveFateCity($data = [])
    {
        if (!empty($data)) {
            $rid = null;
            $inserts = [];
            // 命运之城城市经纬度已内置入库
            $citys = config('city.lon_lat');// 经纬度

            foreach ($data as $f) {
                foreach ($citys as $i => $c) {
                    if ($f['longitude'] == $c[0] && $f['latitude'] == $c[1]) {
                        if ($rid === null) $rid = $f['rid'];

                        $inserts[] = ['mid' => $i + 1, 'fcid' => $f['id'], 'uid' => $f['uid'], 'rid' => $f['rid']];
                    }
                }
            }
            if (!empty($inserts)) {
                try {
                    // 先删除当前档案的命运之城
                    $this->where('rid', $rid)->delete();

                    $this->insert($inserts);

                } catch (\Exception $e) {

                    \Log::info('命运之城写入失败：' . json_encode($inserts, true). 'fate_city_error');
                }
            }
        }
    }

    /**
     * 删除用户已生成的命运之城
     * @param array $map
     * uid int must 用户id
     * rid int must 档案id
     */
    public function removeFateCity($map = [])
    {
        if (!empty($map) && isset($map['uid']) && $map['uid'] && isset($map['rid']) && $map['rid'] ) {
            try {
                // 先删除当前档案的命运之城
                $this->where($map)->delete();

                Cache::rm('fate_city_' . $map['rid']);
            } catch (\Exception $e) {
                \think\Log::write('命运之城删除失败：', 'fate_city_error', true);
            }
        }
    }
}
